package com.shuo.dsa.leetcode;

import com.shuo.dsa.model.ListNode;

/**
 * 对链表进行排序, 要求复杂度 nlogn
 * 思路: 先用快慢指针求得中点节点, 然后截断后用归并
 */
public class SortList {

    public ListNode sortList(ListNode head) {
        if (head == null) return null;
        if (head.next == null) return head;
        ListNode fast = head;
        ListNode slow = head;
        ListNode cut = null;
        while (fast != null && fast.next != null) {
            cut = slow;
            slow = slow.next;
            fast = fast.next.next;
        }
        cut.next = null;
        ListNode n1 = sortList(head);
        ListNode n2 = sortList(slow);
        return merge(n1, n2);
    }


    private ListNode merge(ListNode list1, ListNode list2) {
        ListNode sentinel = new ListNode(0);
        ListNode newList = sentinel;
        while (list1 != null && list2 != null) {
            if (list1.val > list2.val) {
                newList.next = list2;
                newList = list2;
                list2 = list2.next;
            } else {
                newList.next = list1;
                newList = list1;
                list1 = list1.next;
            }
        }
        if (list1 != null)
            newList.next = list1;
        if (list2 != null)
            newList.next = list2;
        return sentinel.next;
    }
}
